package com.service.socket.server;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import com.service.other.ServerConfig;

public class VehicleServer {
	
	private int port = ServerConfig.instance().server_port;
	
	private int maxSize = 5000;
	
	private ServerBootstrap bootstrap;
	
	public ChannelGroup channelGroup = new DefaultChannelGroup();

	private static VehicleServer server = new VehicleServer();
	
	public static VehicleServer instance() {
        return server;
    }
	
	public void run(){
		NioServerSocketChannelFactory nioscf = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());		
		this.bootstrap = new ServerBootstrap(nioscf);
		this.bootstrap.setOption("child.tcpNoDelay",true);	
		this.bootstrap.setOption("child.keepAlive", true);
		ChannelPipelineFactory cpf = new ChannelPipelineFactory(){
				byte[] bytes={0x55};
				final ChannelBuffer buff=ChannelBuffers.copiedBuffer(bytes);
				public ChannelPipeline getPipeline() {  
	                ChannelPipeline pipeline = Channels.pipeline();  
	                pipeline.addLast("framer", new DelimiterBasedFrameDecoder(maxSize,buff)); 
	                pipeline.addLast("handler", new VehicleChannelHandler());
	                return pipeline;  
	            }
		};
		this.bootstrap.setPipelineFactory(cpf);
		Channel serverChannel = this.bootstrap.bind(new InetSocketAddress(this.port));
		this.channelGroup.add(serverChannel);
		System.out.println("启动服务器成功");
	}
	
	public void stop(){
		if(this.bootstrap != null){
			//关闭相关管道
			VehicleServer.instance().channelGroup.close().awaitUninterruptibly();
			//资源释放
			this.bootstrap.releaseExternalResources();
		}
	}
}
